package com.gitee.btssplib.sample

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.gitee.btssplib.sample.R
import kotlinx.android.synthetic.main.activity_devices.*

class DevicesActivity : Activity() {

    companion object {
        const val TAG = "DevicesActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_devices)

        val data = BluetoothAdapter.getDefaultAdapter().bondedDevices.toMutableList()
        recyclerView.layoutManager = LinearLayoutManager(this)
        val deviceAdapter = DeviceAdapter(R.layout.devices_item, data)

        deviceAdapter.setOnItemClickListener { adapter, view, position ->
            Log.d(TAG, "OnClick.position=$position")
            val intent = Intent()
            intent.putExtra("bluetoothDevice", data[position])
            setResult(RESULT_OK, intent)
            finish()
        }
        recyclerView.adapter = deviceAdapter
    }

    class DeviceAdapter(layoutResId: Int, data: MutableList<BluetoothDevice>?) : BaseQuickAdapter<BluetoothDevice, BaseViewHolder>(layoutResId, data) {

        override fun convert(helper: BaseViewHolder?, item: BluetoothDevice?) {
            helper?.setText(R.id.textView, "${item?.name} / ${item?.address}")
        }
    }
}
